package com.xdwanj.criminalintent.activity;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.xdwanj.criminalintent.R;
import com.xdwanj.criminalintent.fragment.CrimeFragment;
import com.xdwanj.criminalintent.fragment.CrimeListFragment;

import java.util.UUID;

public class MainActivity extends AppCompatActivity implements CrimeListFragment.Callbacks {
    private final static String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //这一句的目的是什么
        Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);

        if (currentFragment == null) { //这一句的目的是什么
            //获得一个CrimeListFragment实例
            CrimeListFragment crimeListFragment = CrimeListFragment.newInstance(); //虽然不知道这个语法哪里妙

            // 通过片段管理器(FragmentManager), 绑定
            getSupportFragmentManager()
                    .beginTransaction() //开始(合同)
                    .add(R.id.fragment_container, crimeListFragment) //添加Fragment
                    .commit(); //提交


            Log.d(TAG, "onCreate: binding fragment is " + getFragmentManager().findFragmentById(R.id.fragment_container));
        }

    }

    /**
     * 实现这个 CrimeListFragment.Callbacks 接口,当CrimeList某个Item被点击后触发,
     * 切换Fragment
     *
     * @param crimeId crimeItem的Id
     */
    @Override
    public void onCrimeSelected(UUID crimeId) { //实现这个 CrimeListFragment.Callbacks 接口
        Log.d(TAG, "onCrimeSelected: " + crimeId);
        CrimeFragment crimeFragment = CrimeFragment.newInstance(crimeId);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, crimeFragment)
                .addToBackStack(null) //把fragment事务添加到回退栈
                .commit();
    }
}